package com.moons.idevices;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.util.Log;
import android.widget.Toast;

import com.moons.idevices.printers.EP261CK;
import com.moons.idevices.printers.Printer;
import com.moons.idevices.printers.PrinterManager;
import com.moons.idevices.printers.RT58C;
import com.moons.idevices.utils.DeviceFilter;
import com.szsicod.print.escpos.PrinterAPI;
import com.szsicod.print.log.AndroidLogCatStrategy;
import com.szsicod.print.log.Logger;
import com.szsicod.print.log.Utils;
import com.tbruyelle.rxpermissions3.RxPermissions;

import java.util.HashMap;
import java.util.List;

import androidx.fragment.app.FragmentActivity;

public class Devices {
    private final String TAG = this.getClass().getSimpleName();


    private Devices() {
    }

    public static Devices getInstance() {
        return DevicesHolder.INSTANCE;
    }

    private static class DevicesHolder {
        private static final Devices INSTANCE = new Devices();
    }

    private Context mContext;


    private void probeDevices(IPrinter iPrinter) {

        final UsbManager mUsbManager = (UsbManager) mContext.getSystemService(Context.USB_SERVICE);
        final List<DeviceFilter> ep261ckFilters = DeviceFilter.getDeviceFilters(mContext, R.xml.ep261ck_device_filter);
        final List<DeviceFilter> rt58cFilters = DeviceFilter.getDeviceFilters(mContext, R.xml.rt58c_device_filter);

        HashMap<String, UsbDevice> deviceList = mUsbManager.getDeviceList();


        for (UsbDevice device : deviceList.values()) {

            Log.d(TAG, "probeDevices VendorId: " + device.getVendorId());
            Log.d(TAG, "probeDevices ProductId: " + device.getProductId());

            for (DeviceFilter rt58cFilter : rt58cFilters) {
//                Log.d(TAG, "probeDevices rt58cFilter.mVendorId: "+rt58cFilter.mVendorId);
//                Log.d(TAG, "probeDevices rt58cFilter.mProductId: "+rt58cFilter.mProductId);
                if (rt58cFilter.matches(device)) {
                    Log.d(TAG, "probeDevices: rt58cFilter match");

                    Printer printer = new RT58C(iPrinter, mContext);

                    PrinterManager.getInstance().setPrinter(printer);

                    printer.connect();

                    return;
                }

            }


            for (DeviceFilter filter : ep261ckFilters) {
//                Log.d(TAG, "probeDevices ep261ckFilters.mVendorId: "+filter.mVendorId);
//                Log.d(TAG, "probeDevices ep261ckFilters.mProductId: "+filter.mProductId);

                if (filter.matches(device)) {
                    Log.d(TAG, "probeDevices: ep261ckFilters match");

                    Printer printer = new EP261CK(iPrinter, mContext, device);
                    PrinterManager.getInstance().setPrinter(printer);

                    printer.connect();


                    return;
                }
            }


        }

        if (PrinterManager.getInstance().getPrinter() == null) {

            Toast.makeText(mContext, "未搜索到支持的打印机", Toast.LENGTH_SHORT).show();

        }


    }

    /**
     * 初始化所以设备
     *
     * @param activity
     * @param initResults
     */
    public void deviceInit(Activity activity, InitResults initResults) {
        mContext = activity.getApplicationContext();


        final RxPermissions rxPermissions = new RxPermissions((FragmentActivity) activity);


        rxPermissions.request(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .subscribe(granter -> {

                    if (granter) {

                        Utils.init(mContext);

                        //PrinterUtils.init(mContext);

                        PrinterAPI.getInstance().setOutput(true);

                        Logger.addLogStrategy(new AndroidLogCatStrategy());


                        probeDevices(new IPrinter() {
                            @Override
                            public void actionResult(boolean success) {

                            }

                            @Override
                            public void onConnected(boolean result) {
                                {

                                    Log.d(TAG, "onConnected: " + result);

                                    initResults.printerConnected(result);
                                    initResults.allInitialized(result);


                                }
                            }
                        });


                    } else {

                        Toast.makeText(activity, "拒绝此权限会导致无法使用打印机", Toast.LENGTH_SHORT).show();


                    }

                });


    }

    public void disconnect() {

        PrinterManager.getInstance().getPrinter().disconnect();

    }


}